/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.im.bean.ImMsgBizUser;
import com.yami.shop.im.bean.ImMsgBizUserHistory;
import com.yami.shop.im.constants.WhoSend;
import com.yami.shop.im.dao.ImMsgBizUserMapper;
import com.yami.shop.im.service.ImMsgBizUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author LZK
 * @date 2021-04-01 17:22:48
 */
@Service
@AllArgsConstructor
public class ImMsgBizUserServiceImpl extends ServiceImpl<ImMsgBizUserMapper, ImMsgBizUser> implements ImMsgBizUserService {

    private final ImMsgBizUserMapper imMsgBizUserMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBizUserLastMsg(ImMsgBizUserHistory imMsgBizUserHistory) {
        ImMsgBizUser imMsgBizUser = this.getOne(new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getSendType, imMsgBizUserHistory.getSendType())
                .eq(ImMsgBizUser::getBizId, imMsgBizUserHistory.getBizId()).eq(ImMsgBizUser::getUserId, imMsgBizUserHistory.getUserId()));
        if (Objects.nonNull(imMsgBizUser)) {
            imMsgBizUser.setEmployeeId(imMsgBizUserHistory.getEmployeeId());
            if (Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.EMPLOYEE)) {
                imMsgBizUser.setUserUnreadNum(imMsgBizUser.getUserUnreadNum() + 1);
            } else if (Objects.equals(imMsgBizUserHistory.getWhoSend(), WhoSend.USER)) {
                imMsgBizUser.setBizUnreadNum(imMsgBizUser.getBizUnreadNum() + 1);
            }
            imMsgBizUser.setLastMsgId(imMsgBizUserHistory.getId());
            imMsgBizUser.setLastMsgType(imMsgBizUserHistory.getType());
            imMsgBizUser.setLastMsgContent(imMsgBizUserHistory.getContent());
            imMsgBizUser.setLastMsgWhoSend(imMsgBizUserHistory.getWhoSend());
            imMsgBizUser.setLastMsgTime(imMsgBizUserHistory.getCreateTime());
            imMsgBizUser.setUpdateTime(LocalDateTime.now());
            this.updateById(imMsgBizUser);
        }
    }

}
